<template>
  <div
    v-loading="log"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <Card>
      <el-form
        :inline="true"
        :model="page"
        class="demo-form-inline"
        style="display: flex; justify-content: space-around"
      >
        <el-form-item label="编码">
          <el-input
            clearable
            v-model="page.search.code"
            placeholder="编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            style="width: auto"
            v-model="page.search.createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input
            clearable
            v-model="page.search.name"
            placeholder="角色名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div style="margin-left: 20px">
        <Button icon="ios-search" @click="findRole">搜索</Button>
        <Button style="margin-left: 20px" @click="reset">重置</Button>
        <Dropdown trigger="click" style="margin-left: 20px">
          <Button type="default" href="javascript:void(0)">
            更多
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <template #list>
            <DropdownMenu>
              <DropdownItem @click.native="showModalAdd('addRole')"
                ><Icon type="md-person-add" /> 新增</DropdownItem
              >
              <DropdownItem
                ><Icon type="md-cloud-download" /> 导入</DropdownItem
              >
              <DropdownItem><Icon type="md-cloud-upload" /> 导出</DropdownItem>
            </DropdownMenu>
          </template>
        </Dropdown>
      </div>
    </Card>

    <el-table :data="tableData" style="width: 100%" max-height="320">
      <el-table-column fixed prop="code" label="序号" width="50">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed prop="code" label="编码" width="150">
      </el-table-column>
      <el-table-column prop="name" label="角色名称"> </el-table-column>
      <el-table-column prop="describes" label="角色描述"> </el-table-column>
      <el-table-column style="" prop="readonly" label="是否内置">
        <template slot-scope="scope">
          <span>{{ scope.row.readonly == 1 ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="tag"
        label="标签"
        :filters="[
          { text: '启用', value: '启用' },
          { text: '禁用', value: '禁用' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status == true ? 'success' : 'info'"
            disable-transitions
            >{{ scope.row.status == true ? "启用" : "禁用" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <div>
            <el-link type="primary" @click="edit(scope.row)"
              ><i class="el-icon-edit"></i> 编辑</el-link
            >
            <el-divider direction="vertical"></el-divider>
            <el-dropdown trigger="click" placement="bottom-start">
              <span class="el-dropdown-link">
                <i class="el-icon-share"></i>
                {{ scope.row.dropdown || "更多"
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu
                slot="dropdown"
                append-to-body
                popper-append-to-body
              >
                <el-dropdown-item
                  icon="el-icon-delete"
                  command="a"
                  divided
                  style="color: #f56c6c"
                  @click.native="remove(scope.$index, tableData, scope.row.id)"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-user"
                  command="b"
                  divided
                  style="color: #409eff"
                  @click.native="findAuthorization(scope.row.id)"
                  >授权</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-setting"
                  command="c"
                  divided
                  style="color: #409eff"
                  @click.native="config(scope.row.id)"
                  >配置</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[5, 15, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 授权 -->
    <Modal
      v-model="modal1"
      draggable
      sticky
      scrollable
      :mask="false"
      title="分配角色成员"
      :width="800"
    >
      <div>
        <div style="text-align: center">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="check"
            filterable
            :left-default-checked="[]"
            :right-default-checked="[]"
            :titles="['全部用户', '已选用户']"
            :button-texts="[]"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}',
            }"
            :data="data"
          >
            <span slot-scope="{ option }">{{ option.label }}</span>
          </el-transfer>
        </div>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button type="primary" @click="Authorization">确认</Button>
        <Button @click="modal1 = false">取消</Button>
      </template>
    </Modal>

    <!-- 配置 -->
    <Modal
      v-model="modal2"
      draggable
      sticky
      scrollable
      :mask="false"
      title="配置菜单资源"
      :width="1000"
    >
      <div style="display: flex; justify-content: space-around; height: 460px">
        <Card>
          <template #title>菜单</template>
          <el-input placeholder="输入菜单关键字进行查找" v-model="filterText">
          </el-input>
          <el-tree
            style="margin-top: 20px"
            :default-checked-keys="[...checkmenu]"
            :filter-node-method="filterNode"
            :data="menusData"
            accordion
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @node-click="handleNodeClick"
            @check-change="handleCheckChange"
            @check="handleCheck"
          >
          </el-tree>
        </Card>

        <Card>
          <template #title>资源{{ label }}</template>
          <el-table
            :data="resourcesData"
            style="width: 100%; height: 340px"
            max-height="400"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column fixed prop="code" label="序号" width="50">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" width="180">
            </el-table-column>
            <el-table-column prop="code" label="权限按钮" width="180">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
            </el-table-column>
          </el-table>
        </Card>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button type="primary" @click="saveConfig">确认</Button>
        <Button @click="modal2 = false">取消</Button>
      </template>
    </Modal>

    <!-- 新增 -->
    <Modal
      v-model="modal3"
      draggable
      sticky
      scrollable
      :mask="false"
      title="新增角色信息"
    >
      <div>
        <Form
          ref="addRole"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="80"
        >
          <FormItem label="编码" prop="code">
            <Input v-model="formValidate.code" placeholder="编码"></Input>
          </FormItem>
          <FormItem label="角色名称" prop="name">
            <Input v-model="formValidate.name" placeholder="角色名称"></Input>
          </FormItem>
          <FormItem label="状态" prop="status">
            <RadioGroup v-model="formValidate.status">
              <Radio label="1" border>启用</Radio>
              <Radio label="0" border>禁用</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="角色描述">
            <Input
              v-model="formValidate.describes"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="角色功能描述"
            ></Input>
          </FormItem>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button type="primary" @click="addRole('addRole')">确认</Button>
        <Button @click="modal3 = false">取消</Button>
      </template>
    </Modal>

    <!-- 编辑 -->
    <Modal
      v-model="modal4"
      draggable
      sticky
      scrollable
      :mask="false"
      title="编辑角色信息"
    >
      <div>
        <Form
          ref="formValidate"
          :model="role"
          :rules="ruleValidate"
          :label-width="80"
        >
          <FormItem label="编码" prop="code">
            <Input v-model="role.code" placeholder="编码"></Input>
          </FormItem>
          <FormItem label="角色名称" prop="name">
            <Input v-model="role.name" placeholder="角色名称"></Input>
          </FormItem>
          <FormItem label="状态" prop="status">
            <RadioGroup v-model="role.status">
              <Radio :label="1" border>启用</Radio>
              <Radio :label="0" border>禁用</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="角色描述">
            <Input
              v-model="role.describes"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="角色功能描述"
            ></Input>
          </FormItem>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button type="primary" @click="updateRole('formValidate')">确认</Button>
        <Button @click="modal4 = false">取消</Button>
      </template>
    </Modal>
  </div>
</template>

<script>
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    return {
      log: true,
      roleId: "", //授权配置角色id
      // 授权
      data: [], //授权所有用户
      check: [], //授权用户拥有的角色
      savecheck: [], //保存用户拥有的角色 拥有不在授权该角色
      // removecheck: [], //要删除用户该角色
      modal1: false, //授权模态框布尔值
      renderFunc(h, option) {
        return (
          <span>
            {option.key} - {option.label}
          </span>
        );
      },

      //配置
      // selectedValue: false,
      checkedNodes: [], //配置选中的菜单
      halfCheckedKeys: [], //配置选中的父级菜单
      a: [], //资源过滤
      label: "", //菜单名称
      modal2: false, //配置模态框布尔值
      configRole: "", //配置角色的所有资源
      filterText: "",
      menusData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      checkmenu: [], //选中的菜单
      nodeId: "", //点击菜单时的id
      resourcesData: [], //登入人资源结果集
      targetResourcesData: [], //配置角色具有资源

      //新增
      modal3: false,
      formValidate: {
        code: "", //角色编码
        name: "", //角色名称
        status: "1", //角色状态
        describes: "", //角色描述
        createUser: "", //创建用户
        createTime: "", //创建时间
      },
      ruleValidate: {
        code: [
          {
            required: true,
            message: "请输入角色编码",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入角色编码名称",
            trigger: "blur",
          },
        ],
      },
      //编辑
      modal4: false,
      role: {
        code: "", //角色编码
        name: "", //角色名称
        status: "1", //角色状态
        describes: "", //角色描述
        createUser: "", //创建用户
        createTime: "", //创建时间
      },
      tableData: [], //结果集
      page: {
        //分页条件
        pageNum: 1,
        pageSize: 5,
        search: {
          code: "", //编码
          createTime: [], //创建时间
          name: "", //角色名称
        },
      },
      total: 0, //总数量
      menus: JSON.parse(sessionStorage.getItem("menus")), //登入用户具有的菜单
      roles: JSON.parse(sessionStorage.getItem("roles")), //登入用户拥有的角色信息
      token: JSON.parse(sessionStorage.getItem("satoken")), //登入用户信息
      resources: JSON.parse(sessionStorage.getItem("resources")), //登入用户具有的权限资源列表
    };
  },
  created() {
    this.findRole(); //分页条件查询所有角色
  },
  methods: {
    showModalAdd(name) {
      this.formValidate = {
        code: "", //角色编码
        name: "", //角色名称
        status: "1", //角色状态
        describes: "", //角色描述
        createUser: "", //创建用户
        createTime: "", //创建时间
      };
      this.$refs[name].resetFields();
      this.modal3 = true;
    },
    /**
     * 新增角色信息
     * @param {*} name
     */
    addRole(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          var now = new Date();
          var month = (now.getMonth() + 1).toString().padStart(2, "0");
          var day = now.getDate().toString().padStart(2, "0");
          this.formValidate.createTime =
            now.getFullYear() +
            "-" +
            month +
            "-" +
            day +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();

          this.formValidate.createUser = this.token.loginId;
          this.axios
            .post("/api/auth/pd_auth_role/addRole", this.formValidate)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.code == 200) {
                this.axios
                  .post("/authority/role/findUserIdRole/" + this.token.loginId)
                  .then((rs) => {
                    if (rs.data.code == 200) {
                      // 存储新数据到sessionStorage
                      sessionStorage.setItem(
                        "roles",
                        JSON.stringify(rs.data.data)
                      );
                      // 手动更新组件的data属性中的roles字段
                      this.roles = JSON.parse(sessionStorage.getItem("roles"));
                      this.findRole();
                      this.modal3 = false;
                      this.$Message.success("成功新增一条数据");
                    }
                  });
              }
            });
        } else {
          this.$Message.error("请输入新增角色信息");
        }
      });
    },
    handleSelectionChange(val) {
      if (this.a.length > 0) {
        this.a.forEach((e) => {
          this.targetResourcesData.forEach((e2, index) => {
            if (e.id == e2.id) {
              this.targetResourcesData.splice(index, 1);
            }
          });
        });
      }
      this.a = val;
      // 过滤掉targetResourcesData数组中已经存在的数据
      const filteredData = val.filter(
        (item) => !this.targetResourcesData.find((d) => d.id === item.id)
      );

      // 将过滤后的新数据添加到targetResourcesData数组中
      this.targetResourcesData.push(...filteredData);
      //判断资源是否被选中，选中则选中对应菜单
      if (val.length > 0) {
        const menuId = val[0].menuId;
        if (this.checkmenu.every((c) => !c.includes(menuId))) {
          // 检查 checkmenu 数组中是否存在包含 menuId 的值，如果不存在，则添加
          this.checkmenu.push(menuId);
        }
      }
      this.multipleSelection = val;
    },
    handleNodeClick(node) {
      this.a = [];
      this.nodeId = node.id;
      this.label = " / " + node.label;
      this.resourcesData = [];
      this.resources.forEach((r) => {
        if (r.menuId == node.id) {
          this.resourcesData.push(r);
        }
      });
      // 在循环之前清空Table的选择项，防止在循环之前不必要地选中一些行
      this.$nextTick(() => {
        // 遍历资源数据
        for (let i = 0; i < this.resourcesData.length; i++) {
          // 获取当前资源的 id 值
          const id = this.resourcesData[i].id;
          // 在目标数据中查找是否存在相同 id 值的数据
          const targetIndex = this.targetResourcesData.findIndex(
            (item) => item.id === id
          );
          // 如果找到了，则表示这是一条重复数据
          if (targetIndex > -1) {
            // 将目标数据中的重复项删除，并将资源数据中对应的项选中
            this.$refs.multipleTable.toggleRowSelection(
              this.resourcesData[i],
              true
            );
          }
        }
      });
    },
    handleCheckChange(checkedKeys, checked) {
      // 第一步：获取树形控件的引用
      const tree = this.$refs.tree; // 替换为你的树形控件的引用

      // 第二步：选择要触发 check 事件的节点
      const selectedNode = tree.getNode(checkedKeys.id); // 根据节点的唯一标识符选择节点

      // 第三步：定义选中状态对象
      const checkedState = {
        checkedNodes: tree.getCheckedNodes(),
        checkedKeys: tree.getCheckedKeys(),
        halfCheckedNodes: tree.getHalfCheckedNodes(),
        halfCheckedKeys: tree.getHalfCheckedKeys(),
      };

      // 第四步：触发 check 事件，并传递参数
      tree.$emit("check", selectedNode, checkedState);
      if (checked) {
        console.log("节点被选中了");
      } else {
        console.log("节点被取消选中了");
        let target = [];
        this.targetResourcesData.forEach((t) => {
          if (t.menuId != checkedKeys.id) {
            target.push(t);
          }
        });
        this.checkmenu = [];
        this.targetResourcesData = target;
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleCheck(checkedNodes, checkedKeys) {
      this.checkedNodes = checkedKeys.checkedKeys; //设置选中的菜单
      this.halfCheckedKeys = checkedKeys.halfCheckedKeys; //设置选中的父级菜单
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.findRole();
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.findRole();
    },
    /**
     * 重置
     */
    reset() {
      this.page.search = {
        code: "", //编码
        createTime: [], //创建时间
        name: "", //角色名称
      };
      this.findRole();
    },
    /**
     * 分页条件查询所有角色
     */
    async findRole() {
      try {
        await fetch("/api/auth/pd_auth_role/findRole", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(this.page),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.code == 11051) {
              this.log = false;
              this.$Message.error(data.msg);
            }
            if (data.code == 200) {
              this.tableData = data.data.list;
              this.total = data.data.total;
              this.log = false;
            }
          });
      } catch (error) {}
    },
    /**
     * 根据id删除角色
     * @param {*} index
     * @param {*} rows
     * @param {*} id
     */
    async remove(index, rows, id) {
      try {
        this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.axios
              .post("/api/auth/pd_auth_role/removeRole/" + id)
              .then((r) => {
                if (r.data.code == 11051) {
                  this.$Message.error(r.data.msg);
                }
                if (r.data.data == true) {
                  rows.splice(index, 1);
                  this.$Message.success("成功删除一条数据");
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } catch (error) {}
    },
    /**
     * 编辑角色
     * @param {*} data
     */
    edit(data) {
      this.role = JSON.parse(JSON.stringify(data));
      this.modal4 = true;

      console.log(data);
      console.log(this.role);
    },
    updateRole(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          var now = new Date();
          this.role.updateTime =
            now.getFullYear() +
            "-" +
            (now.getMonth() + 1) +
            "-" +
            now.getDate() +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();

          this.role.updateUser = this.token.loginId;
          console.log(this.role);
          this.axios
            .post("/api/auth/pd_auth_role/updateRole", this.role)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.code == 200) {
                this.findRole();
                this.modal4 = false;
                this.$Message.success("成功编辑一条数据!");
              }
            });
        } else {
          this.$Message.error("请输入编辑角色信息");
        }
      });
    },
    /**
     * 查询所有用户和用户具有的角色
     * @param {*} id
     */
    findAuthorization(id) {
      this.roleId = id; //授权角色id
      this.data = []; //清空用户
      this.check = []; //清空拥有的角色的用户
      this.savecheck = []; //清空保存用户拥有的角色 拥有不在授权该角色
      let i = 0;
      console.log(this.roles);
      this.roles.forEach((role) => {
        if (role.id == id) {
          i = role.id;
        }
      });
      if (i > 0) {
        this.axios
          .post(
            "/api/auth/pd_auth_role/findAuthorization/" +
              id +
              "/" +
              this.token.loginId
          )
          .then((r) => {
            r.data.data.users.forEach((user) => {
              this.data.push({
                key: user.id,
                label: user.name,
              });
            });
            r.data.data.userId.forEach((id) => {
              r.data.data.users.forEach((user) => {
                if (id == user.id) {
                  this.check.push(id);
                  this.savecheck.push(id);
                }
              });
            });
            this.modal1 = true;
          });
      } else {
        this.$Message.error("没有该角色无法授权");
      }
    },
    Authorization() {
      try {
        let add = [];
        let remove = [];
        //判断用户是否拥有该角色
        if (this.savecheck.length > 0) {
          if (this.check.length > 0) {
            //查找选中的数组不包含用户拥有的角色
            add = this.check.filter((item) => !this.savecheck.includes(item));
            //查找用户是否还拥有该角色
            remove = this.savecheck.filter(
              (item) =>
                !this.check
                  .filter((item) => this.savecheck.includes(item))
                  .includes(item)
            );
          } else {
            //没选中代表要收回角色
            remove = this.savecheck;
          }
        } else {
          //没拥有就添加选中的
          add = this.check;
        }
        //判断授权或者回收其中一个不能为空 否则提示：“请选择要授予的用户”
        if (add.length > 0 || remove.length > 0) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          var now = new Date();
          var timestamp =
            now.getFullYear() +
            "-" +
            (now.getMonth() + 1) +
            "-" +
            now.getDate() +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();

          this.axios
            .post("/api/auth/pd_auth_role/batchAuthorization", {
              adds: add,
              removes: remove,
              roleId: this.roleId,
              createUserId: this.token.loginId,
              createTime: timestamp,
            })
            .then((r) => {
              loading.close();
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.data == true) {
                this.modal1 = false;
                this.$Message.success("成功授权");
              }
            });
        } else {
          this.$Message.error("请选择要授予的用户");
        }
      } catch (error) {}
    },
    config(id) {
      try {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.clearSelection();
        this.checkedNodes = [];
        this.halfCheckedKeys = [];
        this.targetResourcesData = [];
        (this.configRole = {}), (this.resourcesData = []);
        this.roleId = id;
        this.modal2 = true;
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.checkmenu = [];
        let menus = [];
        this.menus.forEach((m1) => {
          if (m1.parentId == 0) {
            var m1 = {
              id: m1.id,
              label: m1.name,
              children: [],
            };
            this.menus.forEach((m2) => {
              if (m1.id == m2.parentId) {
                var m2 = {
                  id: m2.id,
                  label: m2.name,
                  children: [],
                };
                m1.children.push(m2);
                this.menus.forEach((m3) => {
                  if (m2.id == m3.parentId) {
                    var m3 = {
                      id: m3.id,
                      label: m3.name,
                    };
                    m2.children.push(m3);
                  }
                });
              }
            });
            menus.push(m1);
          }
        });
        this.menusData = menus;
        //根据角色id查询具有的菜单和资源
        this.axios
          .post("/api/auth/pd_auth_role/findConfig/" + this.roleId)
          .then((r) => {
            if (r.data.code == 200) {
              this.configRole = JSON.parse(JSON.stringify(r.data.data));
              let check = [];
              r.data.data.menus.forEach((m1) => {
                if (m1.parentId == 0) {
                  r.data.data.menus.forEach((m2) => {
                    if (m1.id == m2.parentId) {
                      check.push(m2.id);
                      r.data.data.menus.forEach((m3) => {
                        if (m2.id == m3.parentId) {
                          check.push(m3.id);
                        }
                      });
                    }
                  });
                }
              });
              this.targetResourcesData = JSON.parse(
                JSON.stringify(r.data.data.resources)
              );
              this.checkmenu = check;
            }
          });
        loading.close();
      } catch (error) {}
    },
    saveConfig() {
      var addMenu = []; //配置角色菜单
      var removeMenu = []; //删除配置菜单
      var addResources = []; //配置角色资源
      var removeResources = []; //删除配置资源
      //判断角色是否拥有该菜单
      if (this.configRole.menus.length > 0) {
        var chkMenu = []; //授权角色拥有的菜单
        var chkResources = []; //授权角色拥有的菜单
        this.configRole.menus.forEach((m) => {
          chkMenu.push(m.id);
        });
        this.halfCheckedKeys.forEach((p) => {
          addMenu.push(p); //添加父级菜单id
        });
        this.checkedNodes.forEach((c) => {
          addMenu.push(c); //添加子级菜单id
        });
        //查找选中的数组不包含用户拥有的菜单
        let checkmenusId = addMenu.filter((item) => !chkMenu.includes(item));
        //查找角色是否还是拥有该菜单
        let removeMenusId = chkMenu.filter(
          (item) =>
            !addMenu.filter((item) => chkMenu.includes(item)).includes(item)
        );
        if (this.configRole.resources.length > 0) {
          this.configRole.resources.forEach((r) => {
            chkResources.push(r.id);
          });
          this.targetResourcesData.forEach((t) => {
            addResources.push(t.id); //添加资源
          });
          //查找选中的数组不包含用户拥有的资源
          var checkResourcesId = addResources.filter(
            (item) => !chkResources.includes(item)
          );
          //查找角色是否还是拥有该资源
          var removeResourcesId = chkResources.filter(
            (item) =>
              !addResources
                .filter((item) => chkResources.includes(item))
                .includes(item)
          );
          addResources = checkResourcesId;
          removeResources = removeResourcesId;
        } else {
          this.targetResourcesData.forEach((t) => {
            addResources.push(t.id); //添加资源
          });
        }
        addMenu = checkmenusId;
        removeMenu = removeMenusId;
        console.log("添加菜单" + addMenu);
        console.log("删除菜单" + removeMenu);
        console.log("添加资源" + addResources);
        console.log("删除资源" + removeResources);
        if (
          addMenu.length > 0 ||
          removeMenu.length > 0 ||
          addResources.length > 0 ||
          removeResources.length > 0
        ) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          var now = new Date();
          var timestamp =
            now.getFullYear() +
            "-" +
            (now.getMonth() + 1) +
            "-" +
            now.getDate() +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();

          this.axios
            .post("/api/auth/pd_auth_role/batchConfig/", {
              roleId: this.roleId, //配置角色的id
              addMenu: addMenu, //批量添加菜单
              removeMenu: removeMenu, //批量删除菜单
              addResources: addResources, //批量添加资源
              removeResources: removeResources, //批量删除资源
              createUserId: this.token.loginId, //创建用户id
              createTime: timestamp, //创建时间
            })
            .then((r) => {
              loading.close();
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.data == true) {
                this.modal2 = false;
                this.$Message.success("成功授权");
              }
            });
        } else {
          this.$Message.error("请选择要授予的角色菜单或资源");
        }
      } else {
        //该角色没有菜单就添加
        if (this.checkedNodes.length > 0) {
          //判断是否选中了菜单
          this.halfCheckedKeys.forEach((p) => {
            addMenu.push(p); //添加父级菜单id
          });
          this.checkedNodes.forEach((c) => {
            addMenu.push(c); //添加子级菜单id
          });
          this.targetResourcesData.forEach((t) => {
            addResources.push(t.id); //添加资源
          });
          if (
            addMenu.length > 0 ||
            removeMenu.length > 0 ||
            addResources.length > 0 ||
            removeResources.length > 0
          ) {
            const loading = this.$loading({
              lock: true,
              text: "Loading",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            var now = new Date();
            var timestamp =
              now.getFullYear() +
              "-" +
              (now.getMonth() + 1) +
              "-" +
              now.getDate() +
              " " +
              now.getHours() +
              ":" +
              now.getMinutes() +
              ":" +
              now.getSeconds();

            this.axios
              .post("/api/auth/pd_auth_role/batchConfig/", {
                roleId: this.roleId, //配置角色的id
                addMenu: addMenu, //批量添加菜单
                removeMenu: removeMenu, //批量删除菜单
                addResources: addResources, //批量添加资源
                removeResources: removeResources, //批量删除资源
                createUserId: this.token.loginId, //创建用户id
                createTime: timestamp, //创建时间
              })
              .then((r) => {
                loading.close();
                if (r.data.code == 11051) {
                  this.$Message.error(r.data.msg);
                }
                if (r.data.data == true) {
                  this.modal2 = false;
                  this.$Message.success("成功授权");
                }
              });
          } else {
            this.$Message.error("请选择要授予的角色菜单或资源");
          }
        } else {
          this.$Message.error("请选择要配置的菜单");
        }
      }
    },
    filterTag(value, row) {
      return (row.status == true ? "启用" : "禁用") === value;
    },
  },
};
</script>
<style>
.block {
  text-align: center;
  margin-top: 40px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
</style>
